/**
 * File Info：com.softisland.config.interceptor.JurisdictionInterceptor.java
 * Created Date：2017年4月28日 上午11:45:08
 * Created User: mys
 */
package com.mys.springboot.config.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import com.mys.springboot.Constants;
import com.mys.springboot.config.annotation.Jurisdiction;
import com.mys.springboot.config.cache.SessionCache;
import com.mys.springboot.model.User;

/**
 * @description 权限拦截器
 * @author mys
 * @version 1.0
 *
 */
public class JurisdictionInterceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(JurisdictionInterceptor.class);
	private static final String loginUrl = "/login.html";
	
	@Resource
	private SessionCache sessionCache;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.debug("Start check Jurisdiction");
		
		if (handler instanceof ParameterizableViewController) {
			return true;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		// 判断是否需要权限控制
		Jurisdiction jurisdiction = handlerMethod.getMethod().getAnnotation(Jurisdiction.class);
		if (jurisdiction == null) {
			jurisdiction = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Jurisdiction.class);
		}
		
		// 不需要判断权限
		if (jurisdiction == null) {
			return true;
		}
		
		User user = Constants.currentUser();
		if (user == null) {
			response.sendRedirect(loginUrl);
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}
